package com.atguigu.wordcount;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author wky
 * @create 2021-07-12-11:12
 */
public class Count1 {
    public static void main(String[] args) throws Exception {
        //创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //读取数据
        DataSource<String> lineDS = env.readTextFile("src/input/word.txt");
        //解析数据
//        FlatMapOperator<String, Tuple2<String, Long>> wordToOneDStream = lineDS.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
//            @Override
//            public void flatMap(String value, Collector<Tuple2<String, Long>> collector) throws Exception {
//                String[] words = value.split(" ");
//                for (String word : words) {
//                    collector.collect(Tuple2.of(word, 1L));
//                }
//            }
//        });
        FlatMapOperator<String, String> wordDStream = lineDS.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                String[] split = s.split(" ");
                for (String s1 : split) {
                    collector.collect(s1);
                }
            }
        });
        MapOperator<String, Tuple2<String, Long>> wordone = wordDStream.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String s) throws Exception {
                return Tuple2.of(s, 1L);
                //return new Tuple2<String,Long>(s, 1L);

            }
        });
        UnsortedGrouping<Tuple2<String, Long>> tuple2UnsortedGrouping = wordone.groupBy(0);
        AggregateOperator<Tuple2<String, Long>> sum = tuple2UnsortedGrouping.sum(1);
        sum.print();


    }
}
